package org.ronghao.androidwifiplatfrom.activity;

import java.io.File;

import org.ronghao.androidwifiplatfrom.Facade;
import org.ronghao.androidwifiplatfrom.R;
import org.ronghao.androidwifiplatfrom.entity.Game;
import org.ronghao.androidwifiplatfrom.utils.AndroidUtil;
import org.ronghao.androidwifiplatfrom.utils.Contants;
import org.ronghao.androidwifiplatfrom.utils.MessageUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Gallery.LayoutParams;
import android.widget.Toast;

public class CreateGameActivity extends Activity {
	// private final String TAG = "CreateGameActivity";
	private int i = 0;// 主页面的第几页
	private View main_view1;
	private View main_view2;
	private View main_view3;
	private AnimationSet manimationSet;
	private CheckBox passwordCheckbox;
	private EditText passwordEditview;
	private EditText titleName;
	private Gallery gameTypeGallery;
	private Spinner gameNumSpinner;
	private Button backBtn;
	private Button forwordBtn;
	private FrameLayout mainlayout;
	private Facade mFacade;
	/**
	 * 按钮的点击事件
	 */
	private OnClickListener onClickListener = new OnClickListener() {


		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.creategame_button_forword:
				switch (i) {
				case 0:
					if (titleName.getText().toString().equals("")) {
						show("游戏名不能为空！");
						return;
					}
					if (passwordCheckbox.isChecked()
							&& passwordEditview.getText().toString().equals("")) {
						show("密码不能为空！");
						return;
					}
					if (passwordCheckbox.isChecked()
							&&passwordEditview.getText().toString().length()<8) {
						show("密码至少8位！");
						return;
					}
					break;
				case 1:
					break;
				case 2:
					Game mGame = new Game();
					String gameName = titleName.getText().toString();
					mGame.setGameName(gameName.equals("") ? "快加入游戏吧" : gameName);
					mGame.setGamePassword(passwordEditview.getText().toString());
					mGame.setGameID((int) gameTypeGallery.getSelectedItemId());
					mGame.setGameTotleNum(gameNumSpinner
							.getSelectedItemPosition() + 2);
					mGame = mFacade.createGame(mGame);
					if (mGame.getId() > 0) {
						show("创建成功");
						Intent intent = new Intent(CreateGameActivity.this,
								GameWaitActivity.class);
						int j=0;
						do {
							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							j++;
						} while (!mFacade.getAPState()&&j<80);
						if (j==80) {
							finish();
							System.exit(0);
						}
						Bundle bundle = new Bundle();
//						String value = mGame.gameToString();
						//TODO:
						String value ="";
						value = MessageUtils.setData(mGame);
						bundle.putString(Contants.COMMUNICATION_GAME, value);
						bundle.putBoolean(Contants.COMMUNICATION_GAME_HOST, true);
						intent.putExtras(bundle);
						startActivity(intent);
					} else {
						show("创建失败");
					}
					break;
				default:
					break;
				}
				i++;
				RefreshBtn();
				break;

			case R.id.creategame_button_back:
				i--;
				RefreshBtn();
				break;
			default:
				break;
			}
		}

		private void RefreshBtn() {
			switch (i) {
			case 0:
				main_view1.setVisibility(View.VISIBLE);
				main_view2.setVisibility(View.INVISIBLE);
				main_view3.setVisibility(View.INVISIBLE);
				backBtn.setEnabled(false);
				forwordBtn.setText("下一步");
				break;
			case 1:
				main_view1.setVisibility(View.INVISIBLE);
				main_view2.setVisibility(View.VISIBLE);
				main_view3.setVisibility(View.INVISIBLE);
				backBtn.setEnabled(true);
				forwordBtn.setText("下一步");
				break;
			case 2:
				main_view1.setVisibility(View.INVISIBLE);
				main_view2.setVisibility(View.INVISIBLE);
				main_view3.setVisibility(View.VISIBLE);
				forwordBtn.setText("创建");
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 密码的复选框的点击事件
	 */
	private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			passwordEditview.setFocusable(isChecked);
			passwordEditview.setFocusableInTouchMode(isChecked);
			passwordEditview.setEnabled(isChecked);
			if (isChecked) {
				passwordEditview.requestFocus();
			} else {
				passwordEditview.clearFocus();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidUtil.setNoTitleBar_Fullscreen(this);
		setContentView(R.layout.creategame_main);

		mFacade = new Facade(getApplicationContext());
		mFacade.closeWifi();
		initView();
	}

	private void initView() {
		mainlayout = (FrameLayout) findViewById(R.id.creategame_main_layout);
		backBtn = (Button) findViewById(R.id.creategame_button_back);
		forwordBtn = (Button) findViewById(R.id.creategame_button_forword);
		main_view1 = LayoutInflater.from(this).inflate(
				R.layout.creategame_main_gameinf01, null);
		main_view2 = LayoutInflater.from(this).inflate(
				R.layout.creategame_main_gameinf02, null);
		main_view3 = LayoutInflater.from(this).inflate(
				R.layout.creategame_main_gameinf03, null);

		titleName = (EditText) main_view1
				.findViewById(R.id.creategame_gamename_editview);
		passwordCheckbox = (CheckBox) main_view1
				.findViewById(R.id.creategame_password_checkbox);
		passwordEditview = (EditText) main_view1
				.findViewById(R.id.creategame_password_editview);
		gameTypeGallery = (Gallery) main_view2
				.findViewById(R.id.creategame_gametype_gridView);
		gameNumSpinner = (Spinner) main_view3
				.findViewById(R.id.creategame_gamenum_spinner);

		mainlayout.addView(main_view1, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		mainlayout.addView(main_view2, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		mainlayout.addView(main_view3, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		main_view2.setVisibility(View.INVISIBLE);
		main_view3.setVisibility(View.INVISIBLE);

		backBtn.setEnabled(false);
		backBtn.setOnClickListener(onClickListener);
		forwordBtn.setOnClickListener(onClickListener);

		passwordCheckbox.setOnCheckedChangeListener(onCheckedChangeListener);

		gameTypeGallery.setAdapter(new GameAdapter(this));
		gameTypeGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				AnimationSet animationSet = new AnimationSet(true);
				if (manimationSet != null && manimationSet != animationSet) {
					ScaleAnimation scaleAnimation = new ScaleAnimation(1.1f,
							(float) (10.0 / 11), 1.1f, (float) (10.0 / 11),
							Animation.RELATIVE_TO_SELF, 0.5f, // 使用动画播放图片
							Animation.RELATIVE_TO_SELF, 0.5f);

					scaleAnimation.setDuration(500); // 动画开始到结束的执行时间(1000 = 1 秒)
					manimationSet.addAnimation(scaleAnimation); // 用于为动画集合对象添加动画对象。
					manimationSet.setFillAfter(true); // 让其保持动画结束时的状态。
					view.startAnimation(manimationSet);
				}
				ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 1.1f,
						1.0f, 1.1f, Animation.RELATIVE_TO_SELF, 0.5f,
						Animation.RELATIVE_TO_SELF, 0.5f);
				scaleAnimation.setDuration(500);
				animationSet.addAnimation(scaleAnimation);
				animationSet.setFillAfter(true);
				view.startAnimation(animationSet);
				manimationSet = animationSet;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	private class GameAdapter extends BaseAdapter {

		private Context mContext;
		private File[] files;

		public GameAdapter(Context context) {
			this.mContext = context;
			this.files = AndroidUtil.getPicFiles();
		}

		@Override
		public int getCount() {
			if (files == null) {
				return 0;
			}
			return files.length;
		}

		@Override
		public Object getItem(int position) {
			if (files == null) {
				return null;
			}
			return files[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = new ImageView(mContext);
				convertView.setLayoutParams(new LayoutParams(
						Contants.GAME_PIC_WIDTH, Contants.GAME_PIC_HEIGHT));
			} else {
				convertView = (ImageView) convertView;
			}
			convertView
					.setBackgroundDrawable(new BitmapDrawable(AndroidUtil
							.readBitMap(mContext,
									files[position].getAbsolutePath(),
									Contants.GAME_PIC_WIDTH,
									Contants.GAME_PIC_HEIGHT)));
			return convertView;
		}

	}

	public void show(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
}
